//
//  DQBaseHomeViewController.swift
//  DQBaseHomeController
//
//  Created by 邓琪 dengqi on 2017/2/8.
//  Copyright © 2017年 YuBei. All rights reserved.
//

import UIKit
/**
 * tag 是从2000 开始的
 */
let DQScreenWidth:CGFloat = UIScreen.main.bounds.size.width
let DQScreenHeight:CGFloat = UIScreen.main.bounds.size.height
let DQTitleFont:UIFont = UIFont.boldSystemFont(ofSize: 14)//标题的大小
let DQTitleHeight:CGFloat = 40.0//标题滚动视图的高度
let DQUnderlineHeight:CGFloat = 4.0//自定义滑动条的高度
let DQDefaultColer:UIColor = UIColor(kshex: "#8991B0")
let DQNavigationHeight:CGFloat = 64//导航栏的高度
let DQButtonStartTag:Int = 2000

class DQBaseHomeViewController: UIViewController,UIScrollViewDelegate {
    
    var DQColer:UIColor = UIColor(kshex: "#2A304A")//标题选中的颜色
    var UnderLineColor:UIColor = UIColor(kshex: "#4972F9")

    var lineLayer = UIView()
    public var titleScrollView: UIScrollView?   //标题滚动视图
    public var contentScollView: UIScrollView?  //管理子控制器View的滚动视图
    public var selectButton: UIButton? //保存选中的按钮
    private var titleSButtons:NSMutableArray = NSMutableArray.init()//保存标题按钮的数组
    var selectIndex:Int = 0//选中的下标
    private var isIninttial:Bool = false//第一次加载的变量
    private let btnScale:CGFloat = 0.0//用于做过度的效果
    private var underline: UIView? //自定义的滑动条
    var underlineWidth: CGFloat = 0// 底线  长度

    override func viewDidLoad() {
        super.viewDidLoad()
        // 防止位置会下移一个导航的高度
        self.navigationController?.navigationBar.isTranslucent = false
        view.backgroundColor = UIColor.white
        setupTitleScrollViewFunction()
        setupContentScrollVewFunction()
        
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if !isIninttial {
            isIninttial = true
            setupAllButtonTitle()
            setupUnderlineFunction()
        }
    }
    // MARK: - 标题滚动视图
    func setupTitleScrollViewFunction() -> Void{
        titleScrollView = UIScrollView.init(frame: CGRect(x: 0, y: 0, width: DQScreenWidth, height: DQTitleHeight))
        titleScrollView?.showsHorizontalScrollIndicator = false
        titleScrollView?.scrollsToTop = false
        titleScrollView?.backgroundColor = UIColor.white
        self.view.addSubview(titleScrollView!)
    
    }
    // MARK: - 内容滚动视图
    func setupContentScrollVewFunction() -> Void {
        contentScollView = UIScrollView.init(frame: CGRect.init(x: 0, y: DQTitleHeight, width: DQScreenWidth, height: DQScreenHeight-DQTitleHeight-DQNavigationHeight))
        self.view.insertSubview(contentScollView!, at: 0)
        contentScollView?.showsHorizontalScrollIndicator = false
        contentScollView?.isPagingEnabled = true
        contentScollView?.bounces = false
        contentScollView?.alwaysBounceVertical = false
        contentScollView?.scrollsToTop = false
        contentScollView?.delegate = self
        
    }
    func setupAllButtonTitle() -> Void {
        
        let count:Int = self.children.count
        let btnW:CGFloat = DQScreenWidth/CGFloat(count)
        self.underlineWidth = btnW - 25
        for  i  in 0..<count {
            let vc: UIViewController = self.children[i]
            
            let button = createTitleBtn(index: i, title: vc.title)
            
            button.tag = DQButtonStartTag+i
            let btnX: CGFloat = CGFloat(i)*btnW

            button.frame = CGRect(x: btnX, y: 0, width: btnW, height: DQTitleHeight-5)
            titleScrollView?.addSubview(button)
            titleSButtons.add(button)
            button.addTarget(self, action: #selector(titleclickAction(sender:)), for: .touchUpInside)
            
        }
        dealBtnClickAction(sender: titleSButtons[selectIndex] as! UIButton)
        
        titleScrollView?.contentSize = CGSize.init(width: CGFloat(count)*btnW, height: DQTitleHeight)
        contentScollView?.contentSize = CGSize.init(width: CGFloat(count)*DQScreenWidth, height: DQScreenWidth-DQTitleHeight-DQNavigationHeight)
        
    }
    
    func createTitleBtn(index: Int, title: String?) -> UIButton {
        let button = UIButton()
        
        button.titleLabel?.font = DQTitleFont
        
        button.setTitleColor(DQDefaultColer, for: .normal)
        button.setTitleColor(DQColer, for: .selected)
        button.setTitle(title, for: .normal)
        
        return button
    }
    
    func setupUnderlineFunction(){
       
        
        let nowTitleButton:UIButton = titleScrollView?.subviews[selectIndex] as! UIButton
        
        let underlineView = UIView.init()
        underlineView.frame = CGRect.init(x: 0, y: DQTitleHeight-DQUnderlineHeight, width: self.underlineWidth, height: DQUnderlineHeight)
        underlineView.backgroundColor = UnderLineColor
        titleScrollView?.addSubview(underlineView)
        underline = underlineView
        
        nowTitleButton.titleLabel?.sizeToFit()
        
//        underline?.frame.size.width = (nowTitleButton.titleLabel?.frame.size.width)! + 10
        underline?.frame.size.width = self.underlineWidth
        
        underline?.center.x = nowTitleButton.center.x
        
        lineLayer.backgroundColor = UIColor.init(red: 0.93, green: 0.93, blue: 0.93, alpha: 1.0)
        lineLayer.frame = CGRect.init(x: 0, y: DQTitleHeight-1, width: DQScreenWidth, height: 1)
        titleScrollView?.addSubview(lineLayer)
        
    
    }

    
    @objc func titleclickAction(sender:UIButton) -> Void {
     
            dealBtnClickAction(sender: sender)
        
    }
    func setupTitleCenterFunction(sender:UIButton) -> Void {
        var offsetX:CGFloat = sender.center.x - DQScreenWidth*0.5
        if offsetX<0 {
            offsetX = 0
        }
        
        let maxoffsetX = (titleScrollView?.contentSize.width)! - DQScreenWidth
        if offsetX>maxoffsetX {
            offsetX = maxoffsetX
        }
        
        titleScrollView?.setContentOffset(CGPoint.init(x: offsetX, y: 0), animated: true)
        
    }
    
    func setupOneChildViewController(index:Int) -> Void {
        if index>=self.children.count {
            return
        }
        let vc:UIViewController = self.children[index]
        if (vc.view.superview != nil) {
            return
        }
        
        let offX = CGFloat(index)*DQScreenWidth
        vc.view.frame = CGRect.init(x: offX, y: 0, width: DQScreenWidth, height: (contentScollView?.frame.size.height)!)
        contentScollView?.addSubview(vc.view)
        
        
    }
    func adjustUnderLine(sender:UIButton) -> Void {
        underline?.frame.size.width = self.underlineWidth
        underline?.center.x = sender.center.x
        
    }
    func selectTitleButton(sender:UIButton) -> Void {
        selectButton?.isSelected = false
        sender.isSelected = true
        let scale:CGFloat = 1 + btnScale
        
        selectButton?.transform = CGAffineTransform.identity
        sender.transform = CGAffineTransform.init(scaleX: scale, y: scale)

        selectButton = sender
        selectedTitle(title: selectButton!.titleLabel!.text.unwrap)
        
    }
    // 给子类使用，知道选了哪个
    func selectedTitle(title: String) {
        
    }
    
    func dealBtnClickAction(sender:UIButton) -> Void {
        let index = sender.tag - DQButtonStartTag
        selectTitleButton(sender: sender)
        setupOneChildViewController(index: index)
        contentScollView?.contentOffset = CGPoint.init(x: CGFloat(index)*DQScreenWidth, y: 0)
        
        UIView.animate(withDuration: 0.15) {
            
            self.adjustUnderLine(sender: sender)
            
        }
        for i in 0..<titleSButtons.count{
            if !(i==index){
                let noSelectBtn:UIButton = titleSButtons[i] as! UIButton
                noSelectBtn.isSelected = false
            
            }
        }
        
        for i in 0..<children.count{
            let chilaCtl:UIViewController = self.children[i]
            if !chilaCtl.isViewLoaded {
                continue
            }
        
            let childVcView:UIView = chilaCtl.view
            if childVcView.isKind(of: UIScrollView.classForCoder()) {
                let scrollView:UIScrollView = childVcView as! UIScrollView
                scrollView.scrollsToTop = (i == index)
                if i == index {
                    
                }
            }
            
        }
        
    }
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let value = scrollView.contentOffset.x/DQScreenWidth
        let leftIndex:Int = Int(value)
        let rightIndex = leftIndex+1
        let scaleRight:CGFloat = scrollView.contentOffset.x/DQScreenWidth - CGFloat(leftIndex)
        let scaleLeft:CGFloat = 1 - scaleRight
        let leftTitleBtn:UIButton = self.titleSButtons[leftIndex] as! UIButton
//        leftTitleBtn.dqButtonColorScale(scaleLeft)
        
        if rightIndex < self.titleSButtons.count {
            let rightTitleBtn:UIButton = self.titleSButtons[rightIndex] as! UIButton
//            rightTitleBtn.dqButtonColorScale(scaleRight)
            rightTitleBtn.transform = CGAffineTransform.init(scaleX: scaleRight*self.btnScale+1, y: scaleRight*self.btnScale+1)
            
        }
        //关闭预加载下一个
//        setupOneChildViewController(index: rightIndex)
    }
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        let index:Int = Int(scrollView.contentOffset.x/DQScreenWidth)
        let button:UIButton = titleSButtons[index] as! UIButton
        dealBtnClickAction(sender: button)
        
    }
    
    

}
